<template>
  <div class="main-box">
    <van-search
      v-model="queryForm.name"
      show-action
      placeholder="请输入搜索关键词"
      @search="getLabels"
    >
      <template #action>
        <div @click="getLabels">搜索</div>
      </template>
    </van-search>
    <van-tag
      class="label"
      size="large"
      round
      type="success"
      v-for="item in labelList"
      :key="item.id"
      :plain="item.checked ? false : true"
      @click="choiceOneLabel(item)"
    >
      <!-- @click="choiceOneLabel(item.id)" -->
      <!-- :color="rgb(item.checked)" -->
      <!-- :color="item.checked ? '#F5A5FC' : '#40E9FF'" -->
      {{ item.labelName }}
    </van-tag>
    <van-row gutter="40" class="bottoms">
      <van-col
        ><van-button type="primary" @click="nextPage"
          >换一换</van-button
        ></van-col
      >
      <van-col
        ><van-button type="primary" @click="submitChoice"
          >选好了</van-button
        ></van-col
      >
    </van-row>
  </div>
</template>

<script>
import { labelGetListService, labelChoiceService } from "@/api/labelAPI";
import { Notify, Toast } from "vant";

export default {
  name: "ChoiceLabel",
  data() {
    return {
      labelList: [],
      total: 0,
      queryForm: {
        name: "",
        size: 25,
        current: 1,
      },
      ids: [],
    };
  },
  created() {
    this.getLabels();
  },
  methods: {
    async getLabels() {
      // 需要基于 dish-id 发送请求，获取编辑对应的详情数据，进行回显
      const {
        data: {
          success = false,
          errorMsg = "",
          data: { rows, totalCount },
          total = 0,
        },
      } = await labelGetListService(this.queryForm);
      this.labelList = rows;
      this.total = totalCount;
    },
    choiceOneLabel(item) {
      this.$set(item, "checked", !item.checked);
    },
    nextPage() {
      const totalPage = Math.ceil(this.total / this.queryForm.size);
      if (totalPage === 1) {
        Toast("没有更多了");
      }
      if (this.current < totalPage) {
        this.current += 1;
      } else {
        this.current = 1;
      }
    },
    async submitChoice() {
      this.ids = [];
      this.labelList.forEach((item, index) => {
        if (item.checked === true) {
          this.ids.push(item.id);
        }
      });
      const {
        data: { success = false, errorMsg = "", data: res, total = 0 },
      } = await labelChoiceService(this.ids);
      Toast(res);
    },
  },
  computed: {
    rgb() {
      return function (checked) {
        if (checked) {
          return "#40E9FF";
        }
        return "#F5A5FC";
      };
    },
  },
};
</script>

<style lang="less" scoped>
.main-box {
  padding: 15px;
  .label {
    margin: 6px 8px;
    height: 30px;
    font-size: 18px;
    padding: 5px 10px;
  }
  .bottoms {
    position: fixed;
    bottom: 10px;
    .van-button {
      width: 120px;
    }
  }
}
</style>